<template>
  <div class="personnel-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">人员管理</span>
          <div class="right-button">
            <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增 </el-button>
            <el-button type="info" :icon="Upload" @click="handleImport"> 导入 </el-button>
            <el-button type="warning" :icon="Download" @click="handleExport"> 导出 </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="姓名" prop="personnelName">
          <el-input
            v-model="queryParams.personnelName"
            placeholder="请输入姓名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="所属供应商" prop="supplierId">
          <el-select
            v-model="queryParams.supplierId"
            placeholder="请选择供应商"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in supplierOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-select
            v-model="queryParams.position"
            placeholder="请选择职位"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="dict in positionOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-select
            v-model="queryParams.level"
            placeholder="请选择级别"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="dict in levelOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="personnelList" style="width: 100%" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="personnelId" label="人员编号" align="center" width="100" />
        <el-table-column prop="personnelName" label="姓名" align="center" width="120" />
        <el-table-column
          prop="supplierName"
          label="所属供应商"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column prop="position" label="职位" align="center" width="120">
          <template #default="scope">
            {{ scope.row.positionName }}
          </template>
        </el-table-column>
        <el-table-column prop="level" label="级别" align="center" width="100">
          <template #default="scope">
            {{ scope.row.levelName }}
          </template>
        </el-table-column>
        <el-table-column prop="monthlyRate" label="人月单价" align="center" width="100">
          <template #default="scope">
            {{ formatAmount(scope.row.monthlyRate) }}
          </template>
        </el-table-column>
        <el-table-column prop="phoneNumber" label="联系电话" align="center" width="150" />
        <el-table-column prop="entryDate" label="入职日期" align="center" width="120" />
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
              {{ scope.row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              link
              :icon="Edit"
              @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button size="small" type="primary" link :icon="View" @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-popconfirm
              :title="`是否确认删除人员'${scope.row.personnelName}'?`"
              @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger" link :icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @update:current-page="val => (queryParams.pageNum = val)"
          @update:page-size="val => (queryParams.pageSize = val)"
        />
      </div>
    </el-card>

    <!-- 表单组件 -->
    <PersonnelForm
      v-if="dialog.visible"
      v-model="dialog.visible"
      :title="dialog.title"
      :personnel="currentPersonnel"
      :supplier-options="supplierOptions"
      @success="getList"
    />

    <!-- 详情组件 -->
    <PersonnelDetail v-if="detailVisible" v-model="detailVisible" :personnel="currentPersonnel" />

    <!-- 导入组件 -->
    <PersonnelImport v-if="importVisible" v-model="importVisible" @success="getList" />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import {
  Plus,
  Upload,
  Download,
  Search,
  Refresh,
  Edit,
  View,
  Delete
} from "@element-plus/icons-vue";
import {
  getPersonnelList,
  getPersonnelInfo,
  deletePersonnel,
  exportPersonnel,
  getSupplierOptions
} from "@/api/attendance/personnel";
import { PersonnelVO, PersonnelQuery, SupplierOption } from "@/types/attendance/personnel";
import { handleLoadError } from "@/utils/error-handler";

// 组件导入
import PersonnelForm from "./components/PersonnelForm.vue";
import PersonnelDetail from "./components/PersonnelDetail.vue";
import PersonnelImport from "./components/PersonnelImport.vue";

export default defineComponent({
  name: "PersonnelManagement",
  components: {
    PersonnelForm,
    PersonnelDetail,
    PersonnelImport
  },
  setup() {
    // 职位选项
    const positionOptions = [
      { value: "0", label: "项目经理" },
      { value: "1", label: "架构师" },
      { value: "2", label: "开发工程师" },
      { value: "3", label: "测试工程师" },
      { value: "4", label: "运维工程师" },
      { value: "5", label: "产品经理" },
      { value: "6", label: "UI设计师" },
      { value: "9", label: "其他" }
    ];

    // 级别选项
    const levelOptions = [
      { value: "01", label: "初级" },
      { value: "02", label: "中级" },
      { value: "03", label: "高级" },
      { value: "04", label: "专家" }
    ];

    // 状态选项
    const statusOptions = [
      { value: "0", label: "在职" },
      { value: "1", label: "离职" }
    ];

    // 供应商选项
    const supplierOptions = ref<SupplierOption[]>([]);

    // 获取职位标签
    const getPositionLabel = (position: string) => {
      const dict = positionOptions.find(item => item.value === position);
      return dict ? dict.label : "";
    };

    // 获取级别标签
    const getLevelLabel = (level: string) => {
      const dict = levelOptions.find(item => item.value === level);
      return dict ? dict.label : "";
    };

    // 金额格式化
    const formatAmount = (amount: number | undefined) => {
      if (amount === undefined) return "-";
      return `¥${amount.toLocaleString("zh-CN", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })}`;
    };

    // 查询参数
    const queryParams = reactive<PersonnelQuery>({
      personnelName: "",
      supplierId: "",
      position: "",
      level: "",
      status: "",
      pageNum: 1,
      pageSize: 10
    });

    // 表格数据
    const personnelList = ref<PersonnelVO[]>([]);
    const loading = ref(false);
    const total = ref(0);

    // 当前选中的人员
    const currentPersonnel = ref<PersonnelVO>({
      personnelId: 0,
      personnelCode: "",
      personnelName: "",
      idNumber: "",
      supplierId: 0,
      supplierName: "",
      gender: "",
      genderName: "",
      birthDate: "",
      phoneNumber: "",
      email: "",
      level: "",
      levelName: "",
      monthlyRate: 0,
      entryDate: "",
      leaveDate: null,
      status: "",
      statusName: "",
      userId: null,
      remark: "",
      createTime: ""
    });

    // 弹窗状态
    const dialog = reactive({
      title: "",
      visible: false
    });
    const detailVisible = ref(false);
    const importVisible = ref(false);

    // 表单引用
    const queryRef = ref<FormInstance>();

    // 获取人员列表
    const getList = async () => {
      loading.value = true;
      try {
        // 过滤掉空值参数，与 handleQuery 保持一致
        const params = {
          ...queryParams,
          personnelName: queryParams.personnelName?.trim() || undefined,
          supplierId: queryParams.supplierId || undefined,
          position: queryParams.position || undefined,
          level: queryParams.level || undefined,
          status: queryParams.status || undefined,
          pageNum: queryParams.pageNum,
          pageSize: queryParams.pageSize
        };

        const res = await getPersonnelList(params);
        personnelList.value = res.data.rows || [];
        total.value = res.data.total || 0;
      } catch (error) {
        handleLoadError(error, "人员列表");
      } finally {
        loading.value = false;
      }
    };

    // 获取供应商选项
    const fetchSupplierOptions = async () => {
      try {
        const res = await getSupplierOptions();
        // 将后端返回的数据格式转换为前端下拉框所需的格式
        supplierOptions.value = res.data.map(item => ({
          value: item.supplierId,
          label: item.supplierName,
          code: item.supplierCode,
          status: item.status
        }));
      } catch (error) {
        handleLoadError(error, "供应商选项");
      }
    };

    // 搜索按钮操作
    const handleQuery = async () => {
      // 过滤掉空值参数
      const params = {
        ...queryParams,
        personnelName: queryParams.personnelName?.trim() || undefined,
        supplierId: queryParams.supplierId || undefined,
        position: queryParams.position || undefined,
        level: queryParams.level || undefined,
        status: queryParams.status || undefined,
        pageNum: queryParams.pageNum,
        pageSize: queryParams.pageSize
      };

      loading.value = true;
      try {
        const res = await getPersonnelList(params);
        personnelList.value = res.data.rows || [];
        total.value = res.data.total || 0;
      } catch (error) {
        handleLoadError(error, "人员列表");
      } finally {
        loading.value = false;
      }
    };

    // 重置按钮操作
    const resetQuery = () => {
      if (queryRef.value) {
        queryRef.value.resetFields();
        // 重置后确保分页参数保持默认值
        queryParams.pageNum = 1;
        queryParams.pageSize = 10;
      }
      handleQuery();
    };

    // 分页操作
    const handleSizeChange = (size: number) => {
      queryParams.pageSize = size;
      getList();
    };

    // 页码操作
    const handleCurrentChange = (page: number) => {
      queryParams.pageNum = page;
      getList();
    };

    // 新增按钮操作
    const handleAdd = () => {
      dialog.title = "添加人员";
      // 先关闭对话框，强制组件重新渲染
      dialog.visible = false;

      // 重置数据
      currentPersonnel.value = {
        personnelId: 0,
        personnelCode: "",
        personnelName: "",
        idNumber: "",
        supplierId: 0,
        supplierName: "",
        gender: "",
        genderName: "",
        birthDate: "",
        phoneNumber: "",
        email: "",
        level: "",
        levelName: "",
        monthlyRate: 0,
        entryDate: "",
        leaveDate: null,
        status: "",
        statusName: "",
        userId: null,
        remark: "",
        createTime: ""
      } as PersonnelVO;

      // 使用nextTick确保DOM更新后再显示对话框
      nextTick(() => {
        dialog.visible = true;
      });
    };

    // 编辑按钮操作
    const handleUpdate = async (row: PersonnelVO) => {
      dialog.title = "修改人员";
      // 确保对话框状态先重置为false，强制组件重新渲染
      dialog.visible = false;

      try {
        const res = await getPersonnelInfo(row.personnelId.toString());
        if (res.data) {
          currentPersonnel.value = res.data;
          // 使用nextTick确保DOM更新后再显示对话框
          nextTick(() => {
            dialog.visible = true;
          });
        }
      } catch (error) {
        handleLoadError(error, "人员详情");
      }
    };

    // 查看按钮操作
    const handleView = async (row: PersonnelVO) => {
      try {
        const res = await getPersonnelInfo(row.personnelId.toString());
        currentPersonnel.value = res.data;
        detailVisible.value = true;
      } catch (error) {
        handleLoadError(error, "人员详情");
      }
    };

    // 删除按钮操作
    const handleDelete = (row: PersonnelVO) => {
      ElMessageBox.confirm(`是否确认删除人员"${row.personnelName}"?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            await deletePersonnel(row.personnelId.toString());
            ElMessage.success("删除成功");
            getList();
          } catch (error) {
            handleLoadError(error, "删除人员失败");
          }
        })
        .catch(() => {});
    };

    // 导出按钮操作
    const handleExport = () => {
      exportPersonnel(queryParams);
    };

    // 导入按钮操作
    const handleImport = () => {
      importVisible.value = true;
    };

    // 重置表单
    const resetForm = () => {
      currentPersonnel.value = {
        personnelId: 0,
        personnelCode: "",
        personnelName: "",
        idNumber: "",
        supplierId: 0,
        supplierName: "",
        gender: "",
        genderName: "",
        birthDate: "",
        phoneNumber: "",
        email: "",
        level: "",
        levelName: "",
        monthlyRate: 0,
        entryDate: "",
        leaveDate: null,
        status: "",
        statusName: "",
        userId: null,
        remark: "",
        createTime: ""
      };
    };

    // 初始化
    onMounted(() => {
      getList();
      fetchSupplierOptions();
    });

    return {
      // 数据
      queryParams,
      personnelList,
      loading,
      total,
      currentPersonnel,
      supplierOptions,
      positionOptions,
      levelOptions,
      statusOptions,

      // 对话框状态
      dialog,
      detailVisible,
      importVisible,

      // 引用
      queryRef,

      // 方法
      getList,
      handleQuery,
      resetQuery,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleUpdate,
      handleView,
      handleDelete,
      handleExport,
      handleImport,
      getPositionLabel,
      getLevelLabel,
      formatAmount,

      // 图标渲染
      Plus,
      Upload,
      Download,
      Search,
      Refresh,
      Edit,
      View,
      Delete
    };
  }
});
</script>

<style lang="scss" scoped>
.personnel-container {
  // padding: 20px;

  .box-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .title {
        font-size: 18px;
        font-weight: bold;
      }

      .right-button {
        display: flex;
        gap: 10px;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
